package com.hjh.usb.accessory.communication

import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

/**
 * @author： hjh
 * @createDate： 2025/6/24 15:46
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object UsbFlow {

    // 当前 USB 连接状态
    private val _usbConnState = MutableStateFlow<ConnectionState>(ConnectionState.Disconnected)
    val usbConnState: StateFlow<ConnectionState> = _usbConnState.asStateFlow()

    // 接收到的 USB 数据流
    private val _dataFlow = MutableSharedFlow<ByteArray>(extraBufferCapacity = 64)
    val dataFlow: SharedFlow<ByteArray> = _dataFlow.asSharedFlow()

    /** 更新当前 USB 连接状态 */
    fun updateConnectionState(state: ConnectionState) {
        _usbConnState.update {
            state
        }
    }

    /** 发送接收到的 USB 数据 */
    suspend fun updateData(data: ByteArray) {
        _dataFlow.emit(data)
    }
}